#include "udpcomm.h"
#include <QDebug>


UdpComm::UdpComm(quint16 localPort, QObject *parent) :QObject(parent),port(localPort)
{
    udpSocket = new QUdpSocket(this);
    if(!udpSocket->bind(QHostAddress::Any, port)){
        emit errorOccurred("端口"+ QString::number(port)+"绑定失败"+ udpSocket->errorString());
        return;
    }
    connect(udpSocket, &QUdpSocket::readyRead, this, &UdpComm::onReadyRead);
}

UdpComm::~UdpComm()
{
    udpSocket->close();
}



void UdpComm::onReadyRead()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress senderAddr;
        quint16 senderPort;
        udpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddr, &senderPort);
        emit dataReceived(datagram, senderAddr, senderPort);
    }
}
